#pragma once
#include <iostream>
#include <string>
#include <strings.h>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "inetAddr.hpp"

using namespace LogModule;

using func_t = std::function<void(int sockfd, const std::string&, InetAddr& client)>;

const int defaultFd = -1;

class UdpServer
{
public:
    UdpServer(const uint16_t port, func_t func) 
        :_sockfd(defaultFd),
         _port(port),
         //_ip(ip),
         _isrunning(false),
         _func(func)
    {}
    void Init()
    {
        // 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd: " << _sockfd;

        // // 绑定Socket信息, ip 端口
        // // 填充Socketaddr_in结构体
        // struct sockaddr_in local;
        // bzero(&local, sizeof(local));
        // local.sin_family = AF_INET;
        // // ip和端口信息一定要发送到网络
        // // 本地格式->网络序列
        // local.sin_port = htons(_port);
        // // ip转成4字节, 再转成网络序列
        // // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // local.sin_addr.s_addr = INADDR_ANY;
        InetAddr addr("0", _port);
        //int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        int n = bind(_sockfd, (struct sockaddr*)&addr.NetAddr(), sizeof(addr.NetAddr()));
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd: " << _sockfd;
    }
    void Start()
    {
        _isrunning = true;
        while(1)
        { 
            char buff[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 收消息
            ssize_t s = recvfrom(_sockfd, buff, sizeof(buff) - 1, 0, (struct sockaddr*)&peer, &len);
            if(s >= 0)
            {
                InetAddr client(peer);
                buff[s] = 0;

                _func(_sockfd, buff, client);
  
                // 发消息
                // std::string echo_string = "server echo@: ";
                // echo_string += buff;
                // sendto(_sockfd, res.c_str(), res.size(), 0, (struct sockaddr*)&peer, len);
            }
            
        }
    }
    ~UdpServer(){}
    
private:
    int _sockfd;
    uint16_t _port;
    //std::string _ip;
    bool _isrunning;
    func_t _func; // 服务器回调函数,处理数据
};



